<template>
    <div class="fillcontain">

        <div class="table_container">
            <el-table                
                :data='tableData'
                max-height="450"
                border
                style="width: 100%"
                >
                 <el-table-column
                    :formatter="indexFormatter"
                    label="序号"
                    align='center'
                    width="70">
                </el-table-column>
                <el-table-column
                    prop="number"
                    label="学号"
                    align='center'
                    width="200">
                    <template slot-scope="scope">  
                        <span style="color:#00d053">{{ scope.row.number }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    prop="grade"
                    label="分数"
                    align='center'
                    width="180">
                    <template slot-scope="scope">  
                        <span style="color:#00d053">{{ scope.row.score }}</span>
                    </template>                    
                </el-table-column>
                <el-table-column
                    prop="grade"
                    label="排名"
                    align='center'
                    width="180">
                    <template slot-scope="scope">  
                        <span style="color:#00d053">{{ scope.row.rank }}</span>
                    </template>                    
                </el-table-column>
            </el-table>
            <!-- 分页 -->
             <el-row>
                <el-col :span="24">
                    <div class="pagination">
                        <el-pagination
                            v-if='pagination.total > 0'
                            :page-sizes="pagination.page_sizes"
                            :page-size="pagination.page_size"
                            :layout="pagination.layout"
                            :total="pagination.total"
                            :current-page.sync='pagination.page_index'
                            @current-change='handleCurrentChange'
                            @size-change='handleSizeChange'>
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- 方法测试按钮 -->   
        <!-- <button class="btn btn-primary" @click="tocompute">计算</button>
        <button class="btn btn-primary" @click="toset">设置</button>
        <button class="btn btn-primary" @click="todelete">删除</button>
        <button class="btn btn-primary" @click="getProfile">获取</button>
        <button class="btn btn-primary" @click="toUpdateInfoShow">更新各人信息表</button> -->
    </div>
</template>

<script>

export default {
  name: "scoresum",
  data() {
    return {
      tableData: [],
      allTableData: [],

      userinit: [],
      computedData: [],
      rankData: [],
      InfoShowData: [],

      //需要给分页组件传的信息
      pagination: {
        page_index: 1, // 当前位于哪页
        total: 0, // 总数
        page_size: 5, // 1页显示多少条
        page_sizes: [5, 10, 15, 20], //每页显示多少条
        layout: "total, sizes, prev, pager, next, jumper" // 翻页属性
      },
    };
  },
  created() {
    this.getScore();
  },
  methods: {
    async getScore(){
      try{
        await this.todelete();
        await this.tocompute();
        await this.toset();
        await this.getProfile();
      }catch(err){console.log(err)}
      
    },    
    async getProfile() {
      // 获取表格数据
      try{
        //GET api/profiles/getscore
        const res = await this.$axios.get("/api/profiles/getscore")        
        //赋值给allTableData，分页时过滤成tableData
        this.allTableData = res.data
        //排序allTableData
        this.allTableData.sort(function(a,b){
              return b.score-a.score;
        });  
        this.setPagination()              
        return res;
      }catch(err){console.log(err)}      
    },
    //delete api/profiles/deletescore
    async todelete(){        
        try{
          const res = await this.$axios.delete("/api/profiles/deletescore")                      
          return res;
        }catch(err){console.log(err)}       
    },    
    async tocompute(){        
        try{
            //请求接口：/api/profiles/getinit
            const res = await this.$axios("/api/profiles/getinit")            
            this.userinit = res.data;
            //找到userinit数组中moduleA、B、C、D、E的最高分数
            let aMax = 0;
            let bMax = 0;
            let cMax = 0;
            let dMax = 0;
            let eMax = 0;

            //学号、分数
            let number=0;
            let score = 0;
            let scoreA = 0;
            let scoreB = 0;
            let scoreC = 0;
            let scoreD = 0;
            let scoreE = 0;
            
            //初始化computedData数组
            this.computedData = [];            
            //找到userinit数组中moduleA、B、C、D、E的最高分数
            for(let i=0;i<this.userinit.length;i++){
                if(this.userinit[i].moduleA > aMax){
                    aMax = this.userinit[i].moduleA;
                }
                if(this.userinit[i].moduleB > bMax){
                    bMax = this.userinit[i].moduleB;
                }
                if(this.userinit[i].moduleC > cMax){
                    cMax = this.userinit[i].moduleC;
                }
                if(this.userinit[i].moduleD > dMax){
                    dMax = this.userinit[i].moduleD;
                }
                if(this.userinit[i].moduleE > eMax){
                    eMax = this.userinit[i].moduleE;
                }
            }
            //遍历userinit数组，计算每个学生的总分
            //总分 = (A/aMax)*12 + (B/bMax)*8 + (C/cMax)*48 + (D/dMax)*12 + (E/eMax)*20
            //如果最高分为零，那么该模块得模块总分
            for(let i=0;i<this.userinit.length;i++){
                //判断最大值是否为零，若为零则不计算
                if(aMax==0){scoreA = 12;}else{
                    scoreA=(this.userinit[i].moduleA/aMax)*12;
                }
                if(bMax==0){scoreB = 8;}else{
                    scoreB=(this.userinit[i].moduleB/bMax)*8;
                }
                if(cMax==0){scoreC = 48;}else{
                    scoreC=(this.userinit[i].moduleC/cMax)*48;
                }
                if(dMax==0){scoreD = 12;}else{
                    scoreD=(this.userinit[i].moduleD/dMax)*12;
                }
                if(eMax==0){scoreE = 20;}else{
                    scoreE=(this.userinit[i].moduleE/eMax)*20;
                }
                score = parseFloat((scoreA+scoreB+scoreC+scoreD+scoreE).toFixed(1));                
                number=this.userinit[i].number;
                this.computedData.push({number:number,score:score});   
            }
            //对computedData数组进行排序
            this.computedData.sort(function(a,b){
                return b.score-a.score;
            });
            //遍历computedData数组,index赋值为rank
            for(let j=0;j<this.computedData.length;j++){
                this.rankData.push({number:this.computedData[j].number,score:this.computedData[j].score,rank:j+1});
            }
            //更新用户信息表
            this.toUpdateInfoShow();    
            //返回一个promise  
            return res;                           
        }catch(err){console.log(err)}
    },    
    async toset(){
        try{
            //POST api/profiles/scoreall，将数据传入Score表中          
            const res = await this.$axios.post("/api/profiles/scoreall",this.rankData)              
            return res;
        }catch(err){console.log(err)}
    },
    async toUpdateInfoShow(){
      try{
        //获取所有用户信息get api/users/getuserinfo
        const res = await this.$axios.get("/api/users/getuserinfo")
        this.InfoShowData = res.data;
        //遍历InfoShowData数组
        for(let i=0;i<this.InfoShowData.length;i++){
          //判断rankData数组中是否有该用户的学号
          //如果有，则将该用户的分数、排名赋值给InfoShowData数组
          //如果没有则将0、0赋值给InfoShowData数组
         let index = this.rankData.findIndex(item => item.number === this.InfoShowData[i].number);
         if(index !== -1){
            this.InfoShowData[i].score = this.rankData[index].score;
            this.InfoShowData[i].rank = this.rankData[index].rank;
         }
         else{
            this.InfoShowData[i].score = 0;
            this.InfoShowData[i].rank = 0;
         }
        }
        //console.log(this.InfoShowData);
        //更新用户信息表POST api/users/updateusers
        const res2 = await this.$axios.post("/api/users/updateusers",this.InfoShowData)
        console.log("已更新用户信息表");
        return res2;
      }catch(err){console.log(err)}
    },
    //实现分页功能
    setPagination() {
            //初始化分页
            this.pagination.total = this.allTableData.length
            this.pagination.currentPage = 1
            this.pagination.pageSize = 5
            //设置分页数据
            this.tableData = this.allTableData.filter((item, index) => {
                return index < this.pagination.pageSize
            })
    },
    //改变每页条数
    handleSizeChange(size) {
            this.pagination.currentPage = 1
            this.pagination.pageSize = size
            this.tableData = this.allTableData.filter((item, index) => {
                return index < this.pagination.pageSize                
            })
    },
    //改变当前页
    handleCurrentChange(currentPage) {
            this.pagination.currentPage = currentPage
            this.tableData = this.allTableData.filter((item, index) => {
                return (index >= (currentPage - 1) * this.pagination.pageSize) && (index < currentPage * this.pagination.pageSize)
            })

    },
    // 序号在分页后延续原序号
    indexFormatter(row,column,cellValue,index) {        
        return index + 1 + (this.pagination.currentPage - 1) * this.pagination.pageSize;

    },
  }
};
</script>
<style scoped>
.fillcontain {
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
}
.btnRight {
  float: right;
}
.pagination {
  text-align: right;
  margin-top: 10px;
}
.table_container{
  text-align: center;
}
</style>